import { Injectable } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { CreateUserDto } from '../user/dto/create-user.dto'
import { UserEntity } from '../user/entities/user.entity'
import { UserService } from '../user/user.service'

@Injectable()
export class AuthService {
  constructor(private readonly userService: UserService, private readonly jwtService: JwtService) {}

  createToken(user: any) {
    return this.jwtService.sign(user)
  }

  // 登录
  async login(user: CreateUserDto) {
    const data: any = await this.userService.login(user)
    const token = this.createToken({
      id: data.username,
      username: data.username,
      email: data.email,
    })
    return Object.assign(data, { token })
  }

  async checkAdmin() {
    return true
  }

  async validateUser(payload: UserEntity) {
    const user = await this.userService.findOne(payload.id)
    return user
  }
}
